package com.example.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ResourceConsumerService {

    @Value("${app.cpu.threads:2}")
    private int cpuThreads;

    @Value("${app.cpu.utilization:20}")
    private int targetCpuUtilization;

    @Value("${app.memory.size-mb:100}")
    private int memorySize;

    private ExecutorService executorService;
    private List<byte[]> memoryConsumer;
    private volatile boolean running = true;

    @PostConstruct
    public void init() {
        this.executorService = Executors.newFixedThreadPool(cpuThreads);
        this.memoryConsumer = new ArrayList<>();
        
        // 启动CPU消耗线程
        startCpuConsumption();
        
        // 分配内存
        allocateMemory();
        
        System.out.println("资源消耗服务已启动");
        System.out.println("CPU线程数: " + cpuThreads);
        System.out.println("目标CPU利用率: " + targetCpuUtilization + "%");
        System.out.println("内存分配: " + memorySize + "MB");
    }

    private void startCpuConsumption() {
        for (int i = 0; i < cpuThreads; i++) {
            executorService.submit(new CpuConsumerTask());
        }
    }

    private void allocateMemory() {
        // 分配指定大小的内存
        int arraySize = 1024 * 1024; // 1MB per array
        for (int i = 0; i < memorySize; i++) {
            byte[] memoryBlock = new byte[arraySize];
            // 填充一些随机数据防止JVM优化
            new Random().nextBytes(memoryBlock);
            memoryConsumer.add(memoryBlock);
        }
    }

    @Scheduled(fixedRate = 30000) // 每30秒检查一次
    public void maintainMemory() {
        // 定期访问内存保持活跃状态
        if (!memoryConsumer.isEmpty()) {
            Random random = new Random();
            int index = random.nextInt(memoryConsumer.size());
            byte[] block = memoryConsumer.get(index);
            // 简单的内存访问操作
            int sum = 0;
            for (int i = 0; i < Math.min(1000, block.length); i++) {
                sum += block[i];
            }
        }
    }

    private class CpuConsumerTask implements Runnable {
        @Override
        public void run() {
            while (running) {
                try {
                    // CPU密集型计算
                    long startTime = System.currentTimeMillis();
                    performCpuIntensiveWork();
                    long endTime = System.currentTimeMillis();
                    
                    // 根据目标CPU利用率调整工作和休息时间
                    long workTime = endTime - startTime;
                    long totalTime = workTime * 100 / targetCpuUtilization;
                    long sleepTime = totalTime - workTime;
                    
                    if (sleepTime > 0) {
                        Thread.sleep(sleepTime);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }

        private void performCpuIntensiveWork() {
            // 执行一些CPU密集型计算
            double result = 0;
            for (int i = 0; i < 1000000; i++) {
                result += Math.sqrt(i) * Math.sin(i) * Math.cos(i);
            }
            
            // 一些字符串操作
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 10000; i++) {
                sb.append("cpu_intensive_work_").append(i);
            }
        }
    }

    public void stop() {
        running = false;
        if (executorService != null) {
            executorService.shutdown();
        }
    }

    public String getStatus() {
        return String.format(
            "CPU线程数: %d, 目标CPU利用率: %d%%, 内存使用: %dMB, 运行状态: %s",
            cpuThreads, targetCpuUtilization, memorySize, running ? "运行中" : "已停止"
        );
    }
} 